import re
from django.contrib.auth.backends import ModelBackend

from users.models import User


def jwt_response_payload_handler(token, user=None, request=None):
    """
    自定义jwt验证成功后返回的值
    :param token:
    :param user:
    :param request:
    :return:
    """
    return {
        'token': token,
        'user_id': user.id,
        'username': user.username
    }


class UsernameMobileAuthBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            if re.match(r"^1[03-9]\d{9}$", username):
                user = User.objects.filter(mobile=username)
            else:
                user = User.objects.filter(username=username)
        except User.DoesNotExist:
            user = None

        if user is not None and user.check_password(password):
            return user

        return None
